package net.piggy.core.socket.handler;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import net.piggy.core.inercept.MethodIntercept;
import net.piggy.core.model.HttpStatement;
import net.piggy.core.session.GatewaySession;
import net.piggy.core.session.dubbo.DubboGatewaySessionFactory;
import net.piggy.core.socket.common.AgreementConstant;
import net.piggy.core.socket.parser.RequestParser;
import net.piggy.core.socket.parser.ResponseParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class RequestForwardHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private final Logger logger = LoggerFactory.getLogger(RequestForwardHandler.class);

    private final DubboGatewaySessionFactory gatewaySessionFactory;

    public RequestForwardHandler(DubboGatewaySessionFactory gatewaySessionFactory) {
        this.gatewaySessionFactory = gatewaySessionFactory;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws IOException {
        logger.info("网关接收请求【消息】 uri：{} method：{}", request.uri(), request.method());
        Channel channel = ctx.channel();
        RequestParser parser = new RequestParser(request);
        String uri = parser.getUri();
        if (null == uri)
            return;
        JSONObject json = parser.parse();
        GatewaySession gatewaySession = gatewaySessionFactory.openSession();
        HttpStatement httpStatement = channel.attr(AgreementConstant.HTTP_STATEMENT).get();
        MethodIntercept methodIntercept = new MethodIntercept(gatewaySession, httpStatement, json);
        Object object = methodIntercept.execute();
//        Object object = gatewaySession.get(httpStatement, json);
        DefaultFullHttpResponse response = new ResponseParser().parse(object);
        channel.writeAndFlush(response);
    }

}
